const router = require('koa-router')()
const dbs = require('../../mysql/index').isconnect()

router.post('/all', async ctx => {
  let { typeid, page, pagesize } = ctx.request.body
  let allcount = await dbs.find('*', 'good', `type=${typeid}`)
  ctx.body = allcount
  // if (typeid == '' || typeid == undefined) {
  if (page == '' || page == undefined) {
    ctx.body = {
      code: 200,
      result: { allnumber: allcount.length, data: allcount },
    }
  } else {
    let res1
    if (typeid == '' || typeid == undefined) {
      res1 = await dbs.other(
        `select * from good limit ${(page - 1) * pagesize},${pagesize}`
        // 'good',
        // `limit ${(page - 1) * pagesize},${pagesize}`
      ).data
    } else {
      res1 = await dbs.find(
        '*',
        'good',
        `type=${typeid} limit ${(page - 1) * pagesize},${pagesize}`
      )
    }
    // console.log(res1)

    ctx.body = {
      code: 200,
      result: {
        allnumber: allcount.length,
        page: page,
        pagesize: pagesize,
        data: res1,
      },
    }
  }
})

router.post('/search', async ctx => {
  let { objkey } = ctx.request.body
  if (objkey == '') {
    ctx.body = { code: 10000, result: '请输入正确的字符串' }
  } else {
    ctx.body = await dbs.find('*', 'good', `name like '%${objkey}%'`)
  }
})

router.post('/detail', async ctx => {
  let { goodid } = ctx.request.body
  if (goodid == '') {
    ctx.body = { code: 10000, result: '商品id不能为空' }
  } else if (goodid === undefined) {
    ctx.body = { code: 10000, result: '未传入商品id' }
  } else {
    let res = await dbs.find('*', 'good', `good_id = ${goodid}`)
    if (res.length === 0) {
      ctx.body = { code: 10000, result: '商品id有误' }
      return
    }
    ctx.body = { code: 200, result: res }
  }
})

module.exports = router.routes()
